//
//  ClubInfoView.swift
//  77Club
//
//  Created by Apple on 2024/8/27.
//

import UIKit

class ClubInfoCell: UITableViewCell {

    var iconImageView = UIImageView()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    var nameLabel = UILabel()
    var timeLabel = UILabel()
    private let dianLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).text("·")
        .alignment(.center).end()
    private let lookButton = UIIconButton(style: .leading(itemSpace: 2))
    private let commitButton = UIIconButton(style: .leading(itemSpace: 2))
    
    var model:ClubHomeInfoItemModel?{
        didSet {
            guard let md = model else { return }

            iconImageView.loadImage(url: md.image,placehold: "Common_picEmpty")
            if md.is_top == 1 {
                // 创建一个包含图片的 NSTextAttachment
                let attachment = NSTextAttachment()
                // 设置要插入的图片
                attachment.image = UIImage(named: "Info_hot")
                // 调整图片的位置和大小（可选）
                attachment.bounds = CGRect(x: 0, y: -5, width: 20, height: 20) // 根据需要调整
                // 创建包含图片的富文本
                let attributedStringWithImage = NSAttributedString(attachment: attachment)
                // 创建一个可变的富文本字符串
                let fullAttributedString = NSMutableAttributedString(string: md.title)
                // 插入图片到指定位置
//                fullAttributedString.append(attributedStringWithImage)
                fullAttributedString.insert(attributedStringWithImage, at: 0)
                nameLabel.attributedText = fullAttributedString
            }else{
                let fullAttributedString = NSMutableAttributedString(string: md.title)
                // 插入图片到指定位置
                nameLabel.attributedText = fullAttributedString
            }
            timeLabel.text = md.time_format
            if md.look == "0" {
                lookButton.setTitle("浏览", for: .normal)
            }else{
                lookButton.setTitle(md.look + "浏览", for: .normal)
            }  
            if md.pinglun == "0" {
                commitButton.setTitle("评论", for: .normal)
            }else{
                commitButton.setTitle(md.pinglun + "评论", for: .normal)
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.addSubview(iconImageView)
        iconImageView.addSubview(shadowView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(timeLabel)
        contentView.addSubview(dianLabel)
        contentView.addSubview(lookButton)
        contentView.addSubview(commitButton)
        
        iconImageView.layer.cornerRadius = 8
        iconImageView.layer.masksToBounds = true
        iconImageView.contentMode = .scaleAspectFill

        nameLabel.font = 16.font_medium
        nameLabel.textColor = "#2E3033".toColor
        nameLabel.numberOfLines = 2
        
        timeLabel.font = 12.font_medium
        timeLabel.textColor = "#AEB0B3".toColor
        
        lookButton.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Info_smallLook".toImage, for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        
        commitButton.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Info_smallCommit".toImage, for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .normal)
            v.titleLabel?.font = 12.font_medium
            v.isUserInteractionEnabled = false
        }
        
        iconImageView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12.0.Scale)
            make.top.equalToSuperview().offset(12.0.Scale)
            make.width.equalTo(136.0.Scale)
            make.height.equalTo(78.0.Scale)
        }
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconImageView.snp.trailing).offset(12.0.Scale)
            make.trailing.equalToSuperview().offset(-12.0.Scale)
            make.top.equalTo(iconImageView)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconImageView.snp.trailing).offset(12.0.Scale)
            make.trailing.equalToSuperview().offset(-130.0.Scale)
            make.bottom.equalTo(iconImageView)
        }
        
        commitButton.snp.makeConstraints { make in
            make.height.equalTo(12.0.Scale)
            make.trailing.equalToSuperview().offset(-16.0.Scale)
            make.centerY.equalTo(timeLabel)
        }
        
        dianLabel.snp.makeConstraints { make in
            make.trailing.equalTo(commitButton.snp.leading)
            make.centerY.equalTo(commitButton)
        }
        
        lookButton.snp.makeConstraints { make in
            make.height.equalTo(12.0.Scale)
            make.trailing.equalTo(commitButton.snp.leading).offset(-25)
            make.centerY.equalTo(timeLabel)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

class ClubInfoTopCateView: UITableViewHeaderFooterView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
         
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var model: [ClubHomeNormalGameTypeModel]? {
        didSet{
            guard let _ = model else { return }
            collectionView.reloadData()
        }
    }
    
    var updateCateData: ((_ cateID: String) -> Void)?
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = "#F7F8FA".toColor
        contentView.backgroundColor = "#F7F8FA".toColor
        
        addSubview(collectionView)
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12.0.Scale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubInfoCateCell.self, forCellWithReuseIdentifier: ClubInfoCateCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        model?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubInfoCateCell.description(), for: indexPath) as? ClubInfoCateCell else { return UICollectionViewCell() }
        cell.model = model?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [ClubHomeNormalGameTypeModel]()
        model?.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        let cateID = models[indexPath.row].id
        model = models
        updateCateData?(cateID)
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let name = model?[indexPath.row].name ?? ""
        let font = 15.font_semiBold
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width
        
        return CGSize(width: width, height: 46.0.Scale)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}


class ClubInfoCateCell: UICollectionViewCell {

    private let contentButton = c_make_ex(UIButton.self)
        .color("#47494D").font(15.font_semiBold)
        .color("#2E3033", state: .selected).end()
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#2E3033").end()
        
    var model:ClubHomeNormalGameTypeModel?{
        didSet{
            guard let md = model else { return }
            contentButton.isSelected = md.isSel
            contentButton.setTitle(md.name, for: .normal)
            lineView.isHidden = !md.isSel
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = .clear
        backgroundColor = .clear
        
        contentView.subviews{
            contentButton
            lineView
        }

        contentButton.isUserInteractionEnabled = false
        
        contentButton.centerHorizontally().centerVertically(offset: -7)
        lineView.height(2).leading(0).trailing(0).centerVertically(offset: 10)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
